package com.wwwarehouse.contract.orders.place_order;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.CircleImageView;
import com.wwwarehouse.common.custom_widget.ClearEditText;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.custom_widget.textinput.TextInputLayout;
import com.wwwarehouse.common.custom_widget.time_pick.ChoosePickerDialog;
import com.wwwarehouse.common.eventbus_event.BackListenerEvent;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ImageloaderUtils;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.common.tools.rsa.StringUtils;
import com.wwwarehouse.contract.bean.ConfirmOrderParams;
import com.wwwarehouse.contract.bean.PlaceOrdersAddShoppingCartBean;
import com.wwwarehouse.contract.bean.PlaceOrdersBrowseGoodsBean;
import com.wwwarehouse.contract.bean.PlaceOrdersGoodsDrtailsBean;
import com.wwwarehouse.contract.core.ContractConstant;
import com.wwwarehouse.contract.event.RefreshShoppCardEvent;
import com.wwwarehouse.contract.orders.NewLineFlexLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import contract.wwwarehouse.com.contract.R;
import de.greenrobot.event.EventBus;


/**
 * 下单-商品详情fragment
 * Created by ShineF on 2017/10/16 0016.
 */

public class PlaceOrdersGoodsDeatilsFragment extends BaseFragment implements View.OnClickListener, TextWatcher {

    private NewLineFlexLayout flexLayout;
    private RelativeLayout mRlPayType;
    private RelativeLayout mRlPayChannel;
    private LinearLayout mItemContent;
    private TextInputLayout mOrdersInputLayout;
    private ClearEditText mCleOrdersNum;
    private List<String> mChannelList;
    private List<String> mTypelList;
    private TextView mTvPayType;
    private TextView mTvPayChannel;
    private TextView mTvDelivery;
    private TextView mTvObligation;
    private TextView mTvGoodsName;
    private TextView mTvReleaseTime;
    private TextView mTvShopName;
    private TextView mTvGoodsStock;
    private TextView mTvGoodsPrice;
    private ImageView mIvGoodsImg;
    private CircleImageView mCircleView;
    private Button mBtnPlaceOrders;
    private Button mBtnShoppingCarts;
    private static final int LOAD_GOODS_DETAILS = 1;
    private StateLayout mStateLayout;
    private PlaceOrdersGoodsDrtailsBean mData;
    private PlaceOrdersGoodsDrtailsBean mBean;
    private int mShoppintNum = -1;
    private String mDemandId;
    private String mPayType = "";
    private String mPayChannel = "";
    private long contractUkid;
    private int mPlaceType = -1;
    private long mtItemPublishUkid;
    private long mResourceUkid;
    private TextView mOldPrice;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_place_orders_details, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        flexLayout = $(R.id.new_line_layout);
        mItemContent = $(R.id.ll_card_item);
        mRlPayType = $(R.id.rl_pay_type);
        mRlPayChannel = $(R.id.rl_pay_channel);
        mTvPayType = $(R.id.tv_pay_type);
        mTvPayChannel = $(R.id.tv_pay_channel);
        mTvDelivery = $(R.id.tv_delivery_item);
        mTvObligation = $(R.id.tv_obligation_item);
        mTvGoodsName = $(R.id.tv_goods_name);
        mIvGoodsImg = $(R.id.iv_goods_icon);
        mCircleView = $(R.id.civ_shop_icon);
        mTvShopName = $(R.id.tv_shop_name);
        mTvReleaseTime = $(R.id.tv_shop_release_time);
        mTvGoodsStock = $(R.id.tv_goods_stock);
        mTvGoodsPrice = $(R.id.tv_goods_price);
        mStateLayout = $(R.id.sl_state);
        mOrdersInputLayout = $(R.id.til_orders_num_layout);
        mCleOrdersNum = $(R.id.cet_orders_num);
        mBtnPlaceOrders = $(R.id.btn_place_orders);
        mBtnShoppingCarts = $(R.id.btn_add_shopping_cart);
        mOldPrice = $(R.id.tv_goods_old_price);
        mTvDelivery.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        mTvObligation.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        mItemContent.setVisibility(View.GONE);
        mStateLayout.showProgressView(true);
        mOrdersInputLayout.setStateNormal();
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof PlaceOrdersBrowseGoodsDetailsFragment) {
            mActivity.setTitle(R.string.goods_details);
        }
    }

    @Override
    public void requestDatas() {

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mChannelList = new ArrayList<>();
        mTypelList = new ArrayList<>();
        mCleOrdersNum.addTextChangedListener(this);
        mRlPayChannel.setOnClickListener(this);
        mRlPayType.setOnClickListener(this);
        mTvDelivery.setOnClickListener(this);
        mTvObligation.setOnClickListener(this);
        mBtnPlaceOrders.setOnClickListener(this);
        mBtnShoppingCarts.setOnClickListener(this);
        mItemContent.setOnClickListener(this);
        flexLayout.setMaxLine(2);

//        flexLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//            @Override
//            public void onGlobalLayout() {
//                int lastIndex = flexLayout.getLastIndex();
//                if (0 != lastIndex) {
//                    TextView tvLast = (TextView) flexLayout.getChildAt(lastIndex);
//                    tvLast.setText("...");
//                    TextView tvLast1 = (TextView) flexLayout.getChildAt(lastIndex - 1);
//                    tvLast1.setText(flexLayout.getChildCount() + "个");
//                }
//                flexLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
//            }
//        });

        Bundle bundle = getArguments();
        if (null != bundle) {
            mDemandId = bundle.getString("demandId");
            mShoppintNum = bundle.getInt("shppingNum");
            PlaceOrdersBrowseGoodsBean.ItemListBean dataBean = bundle.getParcelable("data");
            if (null != dataBean && null != mDemandId) {
                mtItemPublishUkid = dataBean.getItemPublishUkid();
                mResourceUkid = dataBean.getResourceUkid();
                requestHttp();
            }
        }
        mStateLayout.setSystemListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestHttp();
            }
        });
    }

    public void requestHttp() {
        Map<String, Object> map = new HashMap<>();
        map.put("demandId", mDemandId);
        map.put("itemPublishUkid", mtItemPublishUkid);
        map.put("resourceUkid", mResourceUkid);
        loadData(ContractConstant.GOODS_DETAILS, map, LOAD_GOODS_DETAILS);
    }

    @Override
    public void onClick(View view) {
        String num = mCleOrdersNum.getText().toString().trim();
        mPayType = mTvPayType.getText().toString().trim();
        mPayChannel = mTvPayChannel.getText().toString().trim();
        if (view.getId() == R.id.rl_pay_type) {
            new ChoosePickerDialog.Builder(mActivity)
                    .setData(mTypelList)
                    .setTitle(getString(R.string.pay_type))
                    .setOnDataSelectedListener(new ChoosePickerDialog.OnSelectedListener() {
                        @Override
                        public void onSelected(String s, int i) {
                            mPayType = s;
                            mTvPayType.setText(s);
                        }

                        @Override
                        public void onCancel() {

                        }
                    })
                    .create()
                    .show();
        } else if (view.getId() == R.id.rl_pay_channel) {
            new ChoosePickerDialog.Builder(mActivity)
                    .setData(mChannelList)
                    .setTitle(getString(R.string.pay_channel))
                    .setOnDataSelectedListener(new ChoosePickerDialog.OnSelectedListener() {
                        @Override
                        public void onSelected(String s, int i) {
                            mPayChannel = s;
                            mTvPayChannel.setText(s);
                        }

                        @Override
                        public void onCancel() {

                        }
                    })
                    .create()
                    .show();
        } else if (view.getId() == R.id.tv_delivery_item) {
            Bundle deliveryBundle = new Bundle();
            deliveryBundle.putLong("contractUkid", contractUkid);
            DeliveryItemFragment deliveryFragment = new DeliveryItemFragment();
            deliveryFragment.setArguments(deliveryBundle);
            pushFragment(deliveryFragment);
        } else if (view.getId() == R.id.tv_obligation_item) {
            Bundle obligationBundle = new Bundle();
            obligationBundle.putLong("contractUkid", contractUkid);
            ObligationItemFragment obligationFragment = new ObligationItemFragment();
            obligationFragment.setArguments(obligationBundle);
            pushFragment(obligationFragment);
        } else if (view.getId() == R.id.btn_place_orders) {
            if (TextUtils.isEmpty(num)) {
                ToastUtils.showToast("请输入订购数量");
                return;
            }
            mPlaceType = 1;
            placeOrders(num);
        } else if (view.getId() == R.id.btn_add_shopping_cart) {
            if (TextUtils.isEmpty(num)) {
                num = "1";
            }
            mPlaceType = 2;
            placeOrders(num);
        } else if (view.getId() == R.id.ll_card_item) {
            hideSoftKeyBoard(mCleOrdersNum);
        }
    }

    public void placeOrders(String num) {
        Map<String, Object> map = new HashMap<>();
        if (mPlaceType == 1) {
            map.put("code", "100");
        } else if (mPlaceType == 2) {
            map.put("code", "80");
        }
        map.put("contractUkid", mData.getContractUkid());
        map.put("demandId", mDemandId);
        map.put("itemPublishUkid", mData.getItemPublishUkid());
        if (mPayType.contains("月")) {
            map.put("payType", "month");
            map.put("payTypeValue", mData.getPayment().getPayMonth());
        } else if (mPayType.contains("周")) {
            map.put("payType", "week");
            map.put("payTypeValue", mData.getPayment().getPayWeek());
        } else if (mPayType.contains("下单")) {
            map.put("payType", "orderPay");
        }
        if (mPayChannel.contains("支付宝")) {
            map.put("payWay", "aliPay");
        } else if (mPayChannel.contains("微信")) {
            map.put("payWay", "wechatPay");
        } else if (mPayChannel.contains("银行")) {
            map.put("payWay", "bank");
        } else if (mPayChannel.contains("线下")) {
            map.put("payWay", "offline");
        }
        map.put("qty", num);
        map.put("resourceUkid", mData.getResourceUkid());
        map.put("supplierBusinessId", mData.getSupplierBusinessId());
        map.put("type", "itemDetail");
        loadData(ContractConstant.ADD_SHOPPING_CART, map, 2);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }


    public void loadData(String url, Map map, int what) {
        NoHttpUtils.httpPost(url, map, new NoHttpUtils.OnResponseListener() {
            @Override
            public void onSucceed(CommonClass commonClass, int i) {
                if (i == LOAD_GOODS_DETAILS) {
                    if ("0".equals(commonClass.getCode())) {
                        mData = JSON.parseObject(commonClass.getData().toString(), PlaceOrdersGoodsDrtailsBean.class);
                        if (null != mData)
                            setData(mData);
                    } else {
                        mStateLayout.setVisibility(View.VISIBLE);
                        mStateLayout.showSystemView(commonClass.getMsg(), true);
                    }
                } else if (i == 2) {
                    if ("0".equals(commonClass.getCode())) {
                        PlaceOrdersAddShoppingCartBean bean = JSON.parseObject(commonClass.getData().toString(), PlaceOrdersAddShoppingCartBean.class);
                        if (mPlaceType == 1) {
                            Bundle bundle = new Bundle();
                            ConfirmOrderParams params = new ConfirmOrderParams();
                            params.setCartItemUkid(String.valueOf(bean.getCartItemUkid()));
                            params.setDemandId(mDemandId);
                            params.setSupplierBusinessId(String.valueOf(mData.getSupplierBusinessId()));
                            params.setLogo(mData.getSupplierLogo());
                            params.setName(mData.getSupplierName());
                            bundle.putSerializable(ContractConstant.KEY_BUNDLE_CONFIRM_ORDER, params);
                            ConfirmOrderFragment fragment = new ConfirmOrderFragment();
                            fragment.setArguments(bundle);
                            pushFragment(fragment);
                        } else {
                            mShoppintNum = bean.getItemCount();
                            mBtnShoppingCarts.setText(StringUtils.getResourceStr(mActivity, R.string.add_shopping_carts, String.valueOf(mShoppintNum)));
                            ToastUtils.showToast(getString(R.string.add_success));
                        }
                    } else if (commonClass.getCode().equals("704002")) { //商品已被下架
                        ToastUtils.showToast(commonClass.getMsg());
                    } else if (commonClass.getCode().equals("704001")) { //当前商品库存不足
                        ToastUtils.showToast(commonClass.getMsg());
                    } else if (commonClass.getCode().equals("70301")) { //购物车商品已经存在
                        ToastUtils.showToast(commonClass.getMsg());
                    }
                }
            }

            @Override
            public void onFailed(String s, int i) {

            }

            @Override
            public void onFinish(int i) {

            }
        }, what);
    }

    private void setData(PlaceOrdersGoodsDrtailsBean bean) {
        this.mBean = bean;
        contractUkid = bean.getContractUkid();
        List<String> tags = bean.getTags();
        LayoutInflater inflater = LayoutInflater.from(mActivity);
        mShoppintNum = bean.getItemCount();
        if (mShoppintNum != -1) {
            mBtnShoppingCarts.setText(StringUtils.getResourceStr(mActivity, R.string.add_shopping_carts, String.valueOf(mShoppintNum)));
        }
        if (null != bean.getItemName())
            mTvGoodsName.setText(bean.getItemName());
        if (null != bean.getSupplierName())
            mTvShopName.setText(bean.getSupplierName());
        if (null != bean.getPublishTime())
            mTvReleaseTime.setText(StringUtils.getResourceStr(mActivity, R.string.release_publish_time, bean.getPublishTime()));
//        mTvGoodsStock.setText(StringUtils.getResourceStr(mActivity, R.string.release_kucun, ));
        if (null != bean.getPrice()) {
            mOldPrice.setVisibility(View.VISIBLE);
            mOldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            mOldPrice.setText(StringUtils.getResourceStr(mActivity, R.string.string_contract_money_price, bean.getPrice()));
        } else {
            mOldPrice.setVisibility(View.GONE);
        }
        mTvGoodsStock.setText(String.format(getString(R.string.release_kucun), bean.getInventoryQty(), bean.getPbQtyUnit()));
        mTvGoodsPrice.setText(StringUtils.getResourceStr(mActivity, R.string.rmb, bean.getPbPrice()));
        ImageloaderUtils.displayRoundImg(bean.getItemUrl(), mIvGoodsImg);
        ImageloaderUtils.displayImg(bean.getSupplierLogo(), mCircleView);
        mCleOrdersNum.setText(String.valueOf(1));
        for (String tag : tags) {
            TextView tv = (TextView) inflater.inflate(R.layout.view_new_line_flex_layout, flexLayout, false);
            tv.setText(tag);
            flexLayout.addView(tv);
        }
        PlaceOrdersGoodsDrtailsBean.PaymentBean payment = bean.getPayment();
        if (null != payment) {
            if (payment.getPayWeek() != 0) {
                if (payment.getPayWeek() == 1) {
                    mTypelList.add(StringUtils.getResourceStr(mActivity, R.string.week_pay, "一"));
                } else if (payment.getPayWeek() == 2) {
                    mTypelList.add(StringUtils.getResourceStr(mActivity, R.string.week_pay, "二"));
                } else if (payment.getPayWeek() == 3) {
                    mTypelList.add(StringUtils.getResourceStr(mActivity, R.string.week_pay, "三"));
                } else if (payment.getPayWeek() == 4) {
                    mTypelList.add(StringUtils.getResourceStr(mActivity, R.string.week_pay, "四"));
                } else if (payment.getPayWeek() == 5) {
                    mTypelList.add(StringUtils.getResourceStr(mActivity, R.string.week_pay, "五"));
                } else if (payment.getPayWeek() == 6) {
                    mTypelList.add(StringUtils.getResourceStr(mActivity, R.string.week_pay, "六"));
                } else if (payment.getPayWeek() == 7) {
                    mTypelList.add(StringUtils.getResourceStr(mActivity, R.string.week_pay, "日"));
                }
            }
            if (payment.getPayMonth() != 0) {
                mTypelList.add(StringUtils.getResourceStr(mActivity, R.string.month_pay, payment.getPayMonth()));
            }
            if (payment.getPayOrderFlag() == 1) {
                mTypelList.add(getString(R.string.orders_pay));
            }
            if (!TextUtils.isEmpty(payment.getAccountBank())) {
                mChannelList.add(getString(R.string.bank));
            }
            if (!TextUtils.isEmpty(payment.getAccountAlipay())) {
                mChannelList.add(getString(R.string.alipay));
            }
            if (!TextUtils.isEmpty(payment.getAccountWechat())) {
                mChannelList.add(getString(R.string.wechat));
            }
            if (payment.getPayOfflineFlag() == 1) {
                mChannelList.add(getString(R.string.offline));
            }
            if (!TextUtils.isEmpty(bean.getPayWay())) {
                switch (bean.getPayWay()) {
                    case "bank":
                        mTvPayChannel.setText(getString(R.string.bank));
                        break;
                    case "aliPay":
                        mTvPayChannel.setText(getString(R.string.alipay));
                        break;
                    case "wechatPay":
                        mTvPayChannel.setText(getString(R.string.wechat));
                        break;
                    case "offline":
                        mTvPayChannel.setText(getString(R.string.offline));
                        break;
                }
            }
            if (!TextUtils.isEmpty(bean.getPayType())) {
                if ("week".equals(bean.getPayType())) {
                    switch (bean.getPayTypeValue()) {
                        case "1":
                            mTvPayType.setText(StringUtils.getResourceStr(mActivity, R.string.week_pay, "一"));
                            break;
                        case "2":
                            mTvPayType.setText(StringUtils.getResourceStr(mActivity, R.string.week_pay, "二"));
                            break;
                        case "3":
                            mTvPayType.setText(StringUtils.getResourceStr(mActivity, R.string.week_pay, "三"));
                            break;
                        case "4":
                            mTvPayType.setText(StringUtils.getResourceStr(mActivity, R.string.week_pay, "四"));
                            break;
                        case "5":
                            mTvPayType.setText(StringUtils.getResourceStr(mActivity, R.string.week_pay, "五"));
                            break;
                        case "6":
                            mTvPayType.setText(StringUtils.getResourceStr(mActivity, R.string.week_pay, "六"));
                            break;
                        case "7":
                            mTvPayType.setText(StringUtils.getResourceStr(mActivity, R.string.week_pay, "日"));
                            break;
                    }
                } else if ("month".equals(bean.getPayType())) {
                    mTvPayType.setText(StringUtils.getResourceStr(mActivity, R.string.month_pay, bean.getPayTypeValue()));
                } else if ("orderPay".equals(bean.getPayType())) {
                    mTvPayType.setText(getString(R.string.orders_pay));
                }
            }
        }
        mItemContent.setVisibility(View.VISIBLE);
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        if (!TextUtils.isEmpty(charSequence.toString())) {
            String ordersNumS = mCleOrdersNum.getText().toString().trim();
            if (!TextUtils.isEmpty(ordersNumS)) {
                long ordersNum = Long.valueOf(ordersNumS);
                if (ordersNum > mBean.getInventoryQty()) {
//                    mOrdersInputLayout.setStateWrong("订购数量不能大于发布库存数");
                    mCleOrdersNum.setText(String.valueOf(mBean.getInventoryQty()));
                } else {
                    mOrdersInputLayout.setStateNormal();
                }
                if (ordersNum == 0) {
                    mOrdersInputLayout.setStateWrong("订购数量不能等于0");
                }
            }
        } else {
            mOrdersInputLayout.setStateNormal();
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }

    public void onEventMainThread(BackListenerEvent backListenerEvent) {
        if (peekFragment() instanceof PlaceOrdersGoodsDeatilsFragment && backListenerEvent.getMsg().equals("PlaceOrdersGoodsDeatilsFragment")) {
            popFragment();
            Intent intent = new Intent("refreshOrdersList");
            intent.putExtra("shopNum", mShoppintNum);
            mActivity.sendBroadcast(intent);
            EventBus.getDefault().post(new RefreshShoppCardEvent("", 0));
        }
    }

}
